package com.skyline.courier.net;

import java.net.SocketAddress;
import java.util.LinkedList;
import java.util.Queue;

public class RoundRobinBalancer implements LoadBalancer {
	private ConnectionManager connectionManager;
	private Queue<SocketAddress> addressQueue = new LinkedList<SocketAddress>();

	@Override
	public void setConnectionManager(ConnectionManager connectionManager) {
		this.connectionManager = connectionManager;
		addressQueue.clear();
		addressQueue.addAll(connectionManager.getConnectedAddress());
	}
	
	@Override
	public Connection next() {
		if(addressQueue.isEmpty()) {
			addressQueue.addAll(connectionManager.getConnectedAddress());
		}
		
		if(addressQueue.isEmpty()) {
			return getClosedConnection();
		}
		
		SocketAddress address = addressQueue.poll();
		while(address != null) {
			Connection connection = connectionManager.getConnection(address);
			if(connection != null && connection.isOpen()) {
				return connection;
			}
			address = addressQueue.poll();
		}
		
		return getClosedConnection();
		
	}
	
	private Connection getClosedConnection() {
		if(!connectionManager.getConnectedAddress().isEmpty()) {
			SocketAddress address = connectionManager.getConnectedAddress().iterator().next();
			return connectionManager.getConnection(address);
		} else if(!connectionManager.getDisconnectAddress().isEmpty()) {
			SocketAddress address = connectionManager.getDisconnectAddress().iterator().next();
			return connectionManager.getConnection(address);
		}
		return null;
	}

}
